RegExp輸出的方式有哪些?
一、RegExp輸出的方式match():
公式:
match(regexp)
new RegExp(regexp)
方法,將內容自動轉型成正規表達式。[""]
,等同於match(/(?:)/)
用簡單例子,來說明match 搭配正規表達式物件:
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);
console.log(found);
// Expected output: Array ["T", "I"]
呈上面說明,用三種不同方法來說明match的情況:
const string = "Hello, World!";
const regex = /Hello/;
const result = string.match(regex);
console.log(result); //['Hello', index: 0, input: 'Hello, World!', groups: undefined]
const pattern = "\\d+";
// \\d+ 會在之後自動轉換為正規表達式,意思是:兩條反斜線`\\`為跳脫字元 (\\轉譯成正規表達式,為一條反斜線),轉譯成\d+,\d(代表0-9的數字),+號代表後面加上一個或是多個數字0-9。
// 一個字串,不是 RegExp ,也沒使用 Symbol.match 方法
const text = "12345";
const result = text.match(pattern); //自動將pattern轉換成正規表達式
console.log(result);
//['12345', index: 0, input: '12345', groups: undefined]
接續上面第二個說明,相當於使用new RegExp(regexp)方法,將內容自動轉型成正規表達式:
const pattern = "\\d+";
const text = "12345";
const regex = new RegExp(pattern);
const result = text.match(regex);
console.log(result);
//['12345', index: 0, input: '12345', groups: undefined]
const str = "Nothing will come of nothing.";
str.match();
// returns [""]
//['', index: 0, input: 'Nothing will come of nothing.', groups: undefined]
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match